package com.blank.site;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.Iterator;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.blank.model.Company;

public class Huangye88Site implements ISite {

	String defaulturl;

	public Huangye88Site() {
		defaulturl = "http://b2b.huangye88.com/jiangmen";
	}

	public void addListByUrl(String u) {

		try {
			InputStream is;
			is = Resources.getResourceAsStream("mybatis-config.xml");
			// 建立Session工厂
			SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
			// 获取Session
			SqlSession session = factory.openSession();
			Elements pages;
			Elements pages2;
			String url = u;
			int count =0;
			do {
				Document doc = Jsoup.connect(url).userAgent("Mozilla").get();
				Elements elements = doc.select(".mach_list2 dl dt");
				pages = doc.select(".page_tag a:contains(下一页)");
				pages2= doc.select(".page_tag a:contains(上一页)");
				url = pages.attr("href");
				Iterator<Element> it = elements.iterator();
				count++;
        
				while (it.hasNext()) {
					
					Element cp = it.next();
					Company company = new Company();
					company.setUrl(cp.select("h4 a").attr("href"));
					company.setSource(defaulturl);
					company.setCompanyname(cp.select("h4 a").html());
					company.setPhone(cp.select("span a").html());
					session.insert(Company.class.getName() + ".add", company);
				}
		
			} while (pages.isEmpty() == false&&!(pages2.isEmpty()==true&&count>1));
			session.commit();
			session.close();

		} catch (IOException e) {

			e.printStackTrace();
		}

	}

	public void run() {
		Document doc;
		try {
			doc = Jsoup.connect(defaulturl).userAgent("Mozilla").get();
			Elements elements = doc.select(".tag_tx ul li a");
			
			for (Element element : elements) {
				this.addListByUrl((element.attr("href")));
			}
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
